// 后端服务器配置
const BASE_URL = 'http://localhost:3000' // 根据实际后端地址修改

// 导入认证工具
const auth = require('./auth.js')

/**
 * 发送HTTP请求的通用方法
 * @param {string} url 请求地址
 * @param {object} options 请求配置
 */
function request(url, options = {}) {
  return new Promise((resolve, reject) => {
    // 获取请求头
    const headers = {
      'Content-Type': 'application/json',
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache',
      ...options.header
    }
    
    // 从本地存储获取token
    try {
      const token = wx.getStorageSync('userToken')
      if (token) {
        headers.Authorization = `Bearer ${token}`
      }
    } catch (error) {
      console.error('获取token失败:', error)
    }
    
    // 添加用户ID到请求头
    try {
      const currentUser = auth.getCurrentUser()
      if (currentUser && currentUser.userId) {
        headers['user-id'] = currentUser.userId
      }
      if(currentUser && currentUser.role) {
        headers['user-role'] = currentUser.role
      }
    } catch (error) {
      console.error('获取用户ID失败:', error)
    }
    
    // 为GET请求添加时间戳参数防止缓存
    let finalUrl = `${BASE_URL}${url}`
    if ((options.method || 'GET') === 'GET') {
      const timestamp = Date.now()
      const separator = url.includes('?') ? '&' : '?'
      finalUrl = `${BASE_URL}${url}${separator}_t=${timestamp}`
    }
    
    console.log('发送请求:', finalUrl, options)
    
    wx.request({
      url: finalUrl,
      method: options.method || 'GET',
      data: options.data || {},
      header: headers,
      timeout: options.timeout || 10000,
      success: (res) => {
        console.log('收到响应:', res.statusCode, res.data)
        
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          // 处理401未授权错误
          if (res.statusCode === 401) {
            // 获取当前页面路径
            const pages = getCurrentPages()
            const currentPage = pages[pages.length - 1]
            const currentRoute = currentPage ? currentPage.route : ''
            
            // 如果当前在忘记密码页面，不进行自动跳转
            if (currentRoute.includes('forgot-password') || currentRoute.includes('change-password')) {
              // 在忘记密码页面，只清除token但不跳转
              try {
                wx.removeStorageSync('userToken')
                wx.removeStorageSync('userInfo')
              } catch (e) {}
            } else {
              // 其他页面正常处理401错误
              // 清除本地存储的用户信息
              try {
                wx.removeStorageSync('userToken')
                wx.removeStorageSync('userInfo')
              } catch (e) {}
              
              // 跳转到登录页面
              wx.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none'
              })
              
              setTimeout(() => {
                wx.redirectTo({
                  url: '/pages/auth/login/index'
                })
              }, 1500)
            }
          }
          
          reject({
            success: false,
            message: res.data?.message || `请求失败 (${res.statusCode})`,
            status: res.statusCode
          })
        }
      },
      fail: (error) => {
        console.error('请求错误:', error)
        reject({
          success: false,
          message: '网络连接失败，请检查网络设置',
          type: 'network'
        })
      }
    })
  })
}

// 便捷方法
function get(url, data) {
  data = data || {};
  return request(url, { method: 'GET', data: data });
}
function post(url, data) {
  data = data || {};
  return request(url, { method: 'POST', data: data });
}
function put(url, data) {
  data = data || {};
  return request(url, { method: 'PUT', data: data });
}
function del(url, data) {
  data = data || {};
  return request(url, { method: 'DELETE', data: data });
}

module.exports = {
  request,
  get,
  post,
  put,
  delete: del
}
